#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include "manager/system_manager.h"
#include "utils/logger.h"

// 全局系统管理器实例
static system_manager_t g_system_manager;
static bool g_running = true;

// 信号处理函数
static void signal_handler(int sig) {
    switch (sig) {
    case SIGINT:
        LOG_INFO("Received SIGINT, shutting down...");
        g_running = false;
        break;
    case SIGTERM:
        LOG_INFO("Received SIGTERM, shutting down...");
        g_running = false;
        break;
    default:
        break;
    }
}

// 设置信号处理
static void setup_signal_handlers(void) {
    struct sigaction sa;
    sa.sa_handler = signal_handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;

    sigaction(SIGINT, &sa, NULL);
    sigaction(SIGTERM, &sa, NULL);

    // 忽略其他可能影响程序的信号
    signal(SIGPIPE, SIG_IGN);
}

// 打印使用帮助
static void print_usage(const char *program_name) {
    printf("Usage: %s [OPTIONS]\n", program_name);
    printf("Options:\n");
    printf("  -h, --help           Show this help message\n");
    printf("  -c, --config FILE    Specify configuration file\n");
    printf("  -d, --daemon         Run as daemon\n");
    printf("  -v, --verbose        Enable verbose logging\n");
    printf("  -q, --quiet          Quiet mode, only errors\n");
    printf("  --device-ip IP       Set device API IP address\n");
    printf("  --device-port PORT   Set device API port\n");
    printf("  --http-ip IP         Set HTTP server IP address\n");
    printf("  --http-port PORT     Set HTTP server port\n");
    printf("\nExamples:\n");
    printf("  %s --device-ip 192.168.1.100 --http-port 8080\n", program_name);
    printf("  %s -c /etc/scene_controller/config.json -d\n", program_name);
}

// 解析命令行参数
static int parse_arguments(int argc, char *argv[], char **config_file, bool *daemon_mode) {
    *config_file = NULL;
    *daemon_mode = false;

    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
            print_usage(argv[0]);
            return 1; // 帮助模式，不启动程序
        }
        else if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--config") == 0) {
            if (i + 1 < argc) {
                *config_file = argv[++i];
            } else {
                fprintf(stderr, "Error: Config file path expected after %s\n", argv[i]);
                return -1;
            }
        }
        else if (strcmp(argv[i], "-d") == 0 || strcmp(argv[i], "--daemon") == 0) {
            *daemon_mode = true;
        }
        else if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbose") == 0) {
            logger_set_level(LOG_LEVEL_DEBUG);
        }
        else if (strcmp(argv[i], "-q") == 0 || strcmp(argv[i], "--quiet") == 0) {
            logger_set_level(LOG_LEVEL_ERROR);
        }
        else if (strcmp(argv[i], "--device-ip") == 0) {
            if (i + 1 < argc) {
                // 这里可以设置设备API IP，需要修改全局配置
                LOG_INFO("Device IP would be set to: %s", argv[++i]);
            } else {
                fprintf(stderr, "Error: IP address expected after %s\n", argv[i]);
                return -1;
            }
        }
        else if (strcmp(argv[i], "--device-port") == 0) {
            if (i + 1 < argc) {
                // 这里可以设置设备API端口，需要修改全局配置
                LOG_INFO("Device port would be set to: %s", argv[++i]);
            } else {
                fprintf(stderr, "Error: Port number expected after %s\n", argv[i]);
                return -1;
            }
        }
        else if (strcmp(argv[i], "--http-ip") == 0) {
            if (i + 1 < argc) {
                // 这里可以设置HTTP服务器IP，需要修改全局配置
                LOG_INFO("HTTP IP would be set to: %s", argv[++i]);
            } else {
                fprintf(stderr, "Error: IP address expected after %s\n", argv[i]);
                return -1;
            }
        }
        else if (strcmp(argv[i], "--http-port") == 0) {
            if (i + 1 < argc) {
                // 这里可以设置HTTP服务器端口，需要修改全局配置
                LOG_INFO("HTTP port would be set to: %s", argv[++i]);
            } else {
                fprintf(stderr, "Error: Port number expected after %s\n", argv[i]);
                return -1;
            }
        }
        else {
            fprintf(stderr, "Error: Unknown option: %s\n", argv[i]);
            print_usage(argv[0]);
            return -1;
        }
    }

    return 0;
}

// 守护进程化
static int daemonize(void) {
    pid_t pid = fork();

    if (pid < 0) {
        LOG_ERROR("Failed to fork for daemon");
        return -1;
    }

    if (pid > 0) {
        // 父进程退出
        exit(0);
    }

    // 子进程继续
    umask(0);

    pid_t sid = setsid();
    if (sid < 0) {
        LOG_ERROR("Failed to create new session");
        return -1;
    }

    if ((chdir("/")) < 0) {
        LOG_ERROR("Failed to change directory to /");
        return -1;
    }

    // 关闭标准文件描述符
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

    // 重定向到 /dev/null
    open("/dev/null", O_RDONLY);
    open("/dev/null", O_WRONLY);
    open("/dev/null", O_WRONLY);

    return 0;
}

// 打印启动横幅
static void print_banner(void) {
    printf("\n");
    printf("=============================================\n");
    printf("      Scene Strategy Control System\n");
    printf("               Version 1.0.0\n");
    printf("=============================================\n");
    printf("\n");
}

// 检查系统依赖
static int check_dependencies(void) {
    // 检查必要的目录
    if (access("config", F_OK) != 0) {
        LOG_WARN("Config directory not found, creating...");
        if (mkdir("config", 0755) != 0) {
            LOG_ERROR("Failed to create config directory");
            return -1;
        }
    }

    if (access("logs", F_OK) != 0) {
        LOG_WARN("Logs directory not found, creating...");
        if (mkdir("logs", 0755) != 0) {
            LOG_ERROR("Failed to create logs directory");
            return -1;
        }
    }

    if (access("data", F_OK) != 0) {
        LOG_WARN("Data directory not found, creating...");
        if (mkdir("data", 0755) != 0) {
            LOG_ERROR("Failed to create data directory");
            return -1;
        }
    }

    return 0;
}

// 加载配置文件（如果有）
static int load_configuration(const char *config_file) {
    if (!config_file) {
        LOG_INFO("No configuration file specified, using defaults");
        return 0;
    }

    LOG_INFO("Loading configuration from: %s", config_file);

    // 这里可以实现从配置文件加载配置的逻辑
    // 目前我们使用默认配置

    return 0;
}

// 初始化系统
static int initialize_system(void) {
    LOG_INFO("Initializing Scene Strategy Control System...");

    // 初始化系统管理器
    int result = system_manager_init(&g_system_manager);
    if (result != SUCCESS) {
        LOG_ERROR("Failed to initialize system manager: %d", result);
        return -1;
    }

    LOG_INFO("System initialized successfully");
    return 0;
}

// 运行主循环
static void run_main_loop(void) {
    LOG_INFO("System is now running. Press Ctrl+C to stop.");

    while (g_running) {
        // 主循环可以在这里添加定期任务或状态检查
        // 目前我们只是等待信号

        // 检查系统状态（可选）
        static time_t last_status_check = 0;
        time_t now = time(NULL);

        if (now - last_status_check >= 60) { // 每分钟检查一次
            // 可以在这里添加系统状态检查逻辑
            last_status_check = now;
        }

        // 休眠一段时间，避免忙等待
        sleep(1);
    }
}

// 清理系统资源
static void cleanup_system(void) {
    LOG_INFO("Shutting down system...");

    system_manager_cleanup(&g_system_manager);

    LOG_INFO("System shutdown completed");
}

// 保存PID文件（守护进程模式）
static int create_pid_file(void) {
    FILE *pid_file = fopen("/var/run/scene_controller.pid", "w");
    if (!pid_file) {
        // 尝试当前目录
        pid_file = fopen("scene_controller.pid", "w");
        if (!pid_file) {
            LOG_WARN("Failed to create PID file");
            return -1;
        }
    }

    fprintf(pid_file, "%d\n", getpid());
    fclose(pid_file);

    return 0;
}

// 删除PID文件
static void remove_pid_file(void) {
    unlink("/var/run/scene_controller.pid");
    unlink("scene_controller.pid");
}

int main(int argc, char *argv[]) {
    char *config_file = NULL;
    bool daemon_mode = false;

    // 打印启动横幅
    print_banner();

    // 初始化日志系统
    if (logger_init("logs/system.log", LOG_LEVEL_INFO) != SUCCESS) {
        fprintf(stderr, "Failed to initialize logger\n");
        return EXIT_FAILURE;
    }

    // 解析命令行参数
    int parse_result = parse_arguments(argc, argv, &config_file, &daemon_mode);
    if (parse_result == 1) {
        // 显示帮助信息后退出
        logger_cleanup();
        return EXIT_SUCCESS;
    } else if (parse_result == -1) {
        // 参数解析错误
        logger_cleanup();
        return EXIT_FAILURE;
    }

    // 检查系统依赖
    if (check_dependencies() != 0) {
        LOG_ERROR("Dependency check failed");
        logger_cleanup();
        return EXIT_FAILURE;
    }

    // 设置信号处理
    setup_signal_handlers();

    // 守护进程化（如果需要）
    if (daemon_mode) {
        LOG_INFO("Starting in daemon mode...");
        if (daemonize() != 0) {
            LOG_ERROR("Failed to daemonize");
            logger_cleanup();
            return EXIT_FAILURE;
        }
        create_pid_file();
    }

    // 加载配置
    if (load_configuration(config_file) != 0) {
        LOG_ERROR("Failed to load configuration");
        if (daemon_mode) remove_pid_file();
        logger_cleanup();
        return EXIT_FAILURE;
    }

    // 初始化系统
    if (initialize_system() != 0) {
        LOG_ERROR("Failed to initialize system");
        if (daemon_mode) remove_pid_file();
        logger_cleanup();
        return EXIT_FAILURE;
    }

    // 运行主循环
    run_main_loop();

    // 清理系统
    cleanup_system();

    // 清理资源
    if (daemon_mode) remove_pid_file();
    logger_cleanup();

    LOG_INFO("Scene Strategy Control System exited successfully");
    return EXIT_SUCCESS;
}
